/*
 * ---------------------------------------------------------------------------
 *  Copyright (c) 2012 Qualcomm Technologies, Inc.  All Rights Reserved.
 *  Qualcomm Technologies Proprietary and Confidential.
 * ---------------------------------------------------------------------------
 *
 */

#include <stdio.h>
#include <linux/input.h>
#include <fcntl.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

#define PWR_KEY_DEVICE "/dev/input/event0"
#define SHUTDOWN_TIME_MS 400
#define NO_ERROR 0
#define ERROR -1

#define LOGI(...) fprintf(stderr, "I:" __VA_ARGS__)


u_int64_t GetSysTimeCnt_ms(void) {
    struct timeval tmp;
    gettimeofday(&tmp, NULL);
    return (tmp.tv_sec * 1000 + tmp.tv_usec / 1000);
}



int main(int argc, char* argv[])
{
        int rc, fd, read_size, keypress=0;
        struct input_event event;
        u_int64_t down_tim = 0;

        /* wait for power key event */
        fd = open(PWR_KEY_DEVICE, O_RDONLY|O_NONBLOCK);
        if (fd < 0) {
                LOGI("open pwr key device failed: %s\n", PWR_KEY_DEVICE);
                return ERROR;
        }

        while (1) {

                read_size = read(fd, &event, sizeof(struct input_event));
                if (read_size > 0 && read_size < sizeof(struct input_event)) {
                        LOGI("read input event error!\n");
                        return ERROR;
                }

                if (read_size > 0 && event.type == EV_KEY && event.code == KEY_POWER) {
                      if (event.value == 1){               
                                keypress = 1;
                                down_tim = GetSysTimeCnt_ms();
                        }  else {
                                keypress = 0;
                        }       
                }

                if(keypress == 1){
                        if( (down_tim + SHUTDOWN_TIME_MS) <  GetSysTimeCnt_ms() ){
                                break;
                        }
                }

                usleep(1000*50);
        }
        system("halt");
        //system("reboot -f");
        return 0;
}
